package kr.co.dongpang.android;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dongpang.domain.ArrayFavorites;
import com.google.gson.Gson;

import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.squareup.picasso.Picasso;
import com.sys.app.cms.IdPassword;

@TargetApi(Build.VERSION_CODES.HONEYCOMB) 
public class HomeFragment2 extends Fragment {

	DecimalFormat df = new DecimalFormat("###,###");

	ArrayList<ArrayFavorites> datas = new ArrayList<ArrayFavorites>();

	class JsonReadTask extends AsyncTask<String, Void, Void> {
		
		String page;
		private ProgressDialog pDialog;

		@Override
		protected void onPreExecute() {
			// Showing progress dialog
//			deleteDirectoryTree(getActivity().getCacheDir());
			
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();				
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {

			page = params[0];
			
			String jUrl = "http://dongpang.co.kr/android/dongpang.v01/home2.php?page=" + page + "&id=" + IdPassword.getId(getActivity()) + "&memberLevel=" + IdPassword.getLevel(getActivity());
			String str = JSONfunctions.getStringfromURL(jUrl);
			Gson gson = new Gson();
			ArrayFavorites[] datas2 = gson.fromJson(str, ArrayFavorites[].class);
			for (ArrayFavorites data : datas2) {
				datas.add(data);
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (pDialog.isShowing()) pDialog.dismiss();
			adapter.notifyDataSetChanged();
			super.onPostExecute(result);
		}

	}
 
	public static void deleteDirectoryTree(File fileOrDirectory) {
	    if (fileOrDirectory.isDirectory()) {
	        for (File child : fileOrDirectory.listFiles()) {
	            deleteDirectoryTree(child);
	        }
	    }

	    fileOrDirectory.delete();
	}		
	
	GridView list;
	MyAdapter adapter;
	
	protected boolean isExistLast;
	private static int listPage;
	
	ArrayList<ArrayFavorites> serverDatas = new ArrayList<ArrayFavorites>();
	
	public HomeFragment2() {
    
	}
	  
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.home, container, false);
		
		int tabString = ((ActionBarActivity) getActivity()).getActionBar().getNavigationMode();
		if(tabString != ActionBar.NAVIGATION_MODE_TABS){
			((ActionBarActivity) getActivity()).getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		}
		
		listPage = 0;

		list = (GridView) rootView.findViewById(R.id.list);

		// Getting adapter by passing xml data ArrayList  

		adapter = new MyAdapter(getActivity(), R.layout.home_row, datas);
		View header = inflater.inflate(R.layout.home_header2, null);
		list.addHeaderView(header);
		list.setAdapter(adapter);
		
		list.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				final int lastItem = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount) {
					if (isExistLast == false) {
						isExistLast = true;
						Log.d("Last", "Last");
						new JsonReadTask().execute(String.valueOf(listPage++), null, null);
						Log.d("Last", "Last:"+listPage);
					}
				} else {
					if (isExistLast == true) {
						isExistLast = false;
					}
				}
			}
		});		
		
		if (serverDatas == null || serverDatas.size() == 0) {
			new JsonReadTask().execute(String.valueOf(listPage++), null, null); 
		}		
		
		
		if (IdPassword.getDs(getActivity()).equals("1")) {
			new getLevelTask().execute(null, null, null);
		}
		

		((Button) rootView.findViewById(R.id.menu1)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), SmCategory.class);
				intent.putExtra("prodName", "여성복");
				intent.putExtra("parent", "1");
				startActivity(intent);
			}
		});

		((Button) rootView.findViewById(R.id.menu2)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), SmCategory.class);
				intent.putExtra("prodName", "남성복");
				intent.putExtra("parent", "2");
				startActivity(intent);
			}
		});

		((Button) rootView.findViewById(R.id.menu3)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), SmCategory.class);
				intent.putExtra("prodName", "아동복");
				intent.putExtra("parent", "3");
				startActivity(intent);
			}
		});

		((Button) rootView.findViewById(R.id.menu4)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), SmCategory.class);
				intent.putExtra("prodName", "가방");
				intent.putExtra("parent", "4");
				startActivity(intent);
			}
		});

		((Button) rootView.findViewById(R.id.menu5)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), SmCategory.class);
				intent.putExtra("prodName", "신발");
				intent.putExtra("parent", "5");
				startActivity(intent);
			}
		});

		((Button) rootView.findViewById(R.id.menu6)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(), SmCategory.class);
				intent.putExtra("prodName", "엑세서리");
				intent.putExtra("parent", "6");
				startActivity(intent);
			}
		});
		
		if (IdPassword.getDs(getActivity()).equals("0")) {
			((Button) rootView.findViewById(R.id.home1)).setText("베스트 인기상품 현황(광고)");
		}else{
			((Button) rootView.findViewById(R.id.home1)).setText("베스트 인기상품 현황");
		}
		
		// 매장 광고상품 현황 
		((Button) rootView.findViewById(R.id.home1)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Fragment fragment = new HomeFragment1();
				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();				
			}
		});
		// 실시간 신상품 현황 
		((Button) rootView.findViewById(R.id.home2)).setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Fragment fragment = new HomeFragment2();
				FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();	
			}
		});		

		return rootView;
	}
	
	class getLevelTask extends AsyncTask<Void, Void, Void>{

		String groupSno;
		
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			
	        JSONObject json = JSONfunctions.getJSONfromURL("http://dongpang.co.kr/android/dongpang.v01/getLevel.php?id="+IdPassword.getId(getActivity()));
	        
	        try {
	        	JSONArray dongpang = json.getJSONArray("dongpang");
	    		JSONObject jobject = dongpang.getJSONObject(0);
	    		groupSno = jobject.getString("groupSno");
	    		
	    	} catch (JSONException e) {
	        	Log.e("log_tag","Error Parsing data" + e.toString()); 
	    	}			
			
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			
			if(!groupSno.equals(IdPassword.getLevel(getActivity()))){
				Toast.makeText(getActivity(), "등급이 조정되었습니다.", Toast.LENGTH_LONG).show();
				
				SharedPreferences sharedPreferences = getActivity().getSharedPreferences("cookie", Context.MODE_PRIVATE);
		        SharedPreferences.Editor editor = sharedPreferences.edit();
		        editor.putString("id", IdPassword.getId(getActivity()));
		        editor.putString("password", IdPassword.getPassword(getActivity()));
		        editor.putString("ds", IdPassword.getDs(getActivity()));
		        editor.putString("level", groupSno);
		        editor.commit();
			}
			
			super.onPostExecute(result);
		}
		
	}
	

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		
		if (data != null) {
			Log.d("", "dataOK");
			switch (requestCode) {
			case MainActivity.LOGIN: {
				Log.d("", "loginOk");
				getActivity().finish();
				startActivity(getActivity().getIntent());
				break;
			}
			}
		} else {
			Log.d("", "loginNull");
		}
		
	}

	class MyAdapter extends ArrayAdapter<ArrayFavorites> {

		protected static final int REQUEST_DETAIL = 0;
		int level;

		public MyAdapter(Context context, int resource, ArrayList<ArrayFavorites> items) {
			super(context, resource, items);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getActivity().getLayoutInflater().inflate(R.layout.home_row, null);
			}

			String imgUrl = "http://dongpang.co.kr/images/userdif/goodsColor/" + getItem(position).img + ".jpg";
			
			Picasso.with(getActivity()).load(imgUrl).fit().centerCrop().into((ImageView) convertView.findViewById(R.id.img)); 
			
			if(getItem(position).myFavorites.equals("on")){
				((ImageView) convertView.findViewById(R.id.myFavorites)).setBackgroundResource(R.drawable.star_on);
			}else{
				((ImageView) convertView.findViewById(R.id.myFavorites)).setBackgroundResource(R.drawable.star_off);
			}			
			
			((TextView) convertView.findViewById(R.id.position)).setText(getItem(position).position);
			((TextView) convertView.findViewById(R.id.goodnm)).setText(getItem(position).goodnm);
			((TextView) convertView.findViewById(R.id.favoritesCount)).setText(getItem(position).favoritesCount);

			if (IdPassword.getDs(getActivity()).equals("")) {
				// 로그아웃
				((TextView) convertView.findViewById(R.id.nomalprice)).setText("회원공개");
				convertView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(getActivity(), LoginNew.class);
						startActivityForResult(intent, MainActivity.LOGIN);
					}
				});				
			} else if (IdPassword.getDs(getActivity()).equals("0")) {
				// 도매
				((TextView) convertView.findViewById(R.id.nomalprice)).setText("절친회원공개");
				// 절친회원 모집 안내 
			} else if (IdPassword.getDs(getActivity()).equals("1")) {
				// 소매
				 
				level = Integer.parseInt(IdPassword.getLevel(getActivity()));
				
				if(level >= 3){
					((TextView) convertView.findViewById(R.id.nomalprice)).setText(df.format(Double.parseDouble(getItem(position).nomalprice)));
					convertView.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent intent = new Intent(getActivity(), SmGood.class);
							intent.putExtra("goodcd", getItem(position).goodcd);
							intent.putExtra("goodnm", getItem(position).goodnm);
							startActivity(intent);
						}
					});					
				}else{
					((TextView) convertView.findViewById(R.id.nomalprice)).setText("정회원이상공개"); 
					convertView.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent intent = new Intent(getActivity(), levelUp.class);
							startActivity(intent);
						}
					});						
				}

			}

			return convertView;
		}

	}

}
